package com.qwt.part_time_api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qwt.part_time_api.mapper.UserMapper;
import com.qwt.part_time_api.pojo.User;
import com.qwt.part_time_api.service.UserService;
import com.qwt.part_time_api.utils.JwtUtil;
import com.qwt.part_time_api.vo.LoginVo;
import com.qwt.part_time_api.vo.Result;
import com.qwt.part_time_api.vo.UserInformationVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @Author 君子慎独
 * @create 2021/12/24 0024 22:19
 */

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result findUserInfoById(Long id) {
        log.info("根据ID查询用户信息");
        UserInformationVo userInfoById = userMapper.findUserInfoById(id);
        return Result.success(userInfoById);
    }

    @Override
    public User findUserInfoByUserName(String account) {
        log.info("根据账号查询基本信息");
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getAccount, account);
        return userMapper.selectOne(wrapper);
    }

    @Override
    public Result findUserByToken(String token) {
        log.info("根据Token查询基本信息");
        String account = JwtUtil.getUsername(token);
        LoginVo userInfoByToken = userMapper.findUserInfoByToken(account);
        return Result.success(userInfoByToken);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int saveUser(User user) {
        log.info("添加用户");
        return userMapper.insert(user);
    }

    @Override
    public Long getUserIdByAccount(String account) {
        log.info("获取账号id");
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(User::getId).eq(User::getAccount, account);
        User user = userMapper.selectOne(wrapper);
        Long id = null;
        if (Objects.nonNull(user)) {
            log.info("用户存在");
            id = user.getId();
        }
        return id;
    }
}
